<template>
  <div class="login">

      <el-form ref="loginForm" :rules="rules" :model="loginForm" class="container" @keydown.13.native="handleLogin">
        <el-form-item>
          <div class="u-face">
            <img  src="../assets/user-face.jpg" alt="">
          </div>
        </el-form-item>
        <el-form-item prop="username">
          <!-- 可以通过 prefix-icon 和 suffix-icon 属性在 input 组件首部和尾部增加显示图标，也可以通过 slot 来放置图标。 -->
          <el-input prefix-icon="myicon myicon-user" v-model="loginForm.username" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="myicon myicon-key" type="password" v-model="loginForm.password" placeholder="密码" @keydown.enter.native="submitLogin('loginForm')"></el-input>
        </el-form-item>
        <el-button type="primary" class="login-btn" @click="handleLogin('loginForm')">登录</el-button>
      </el-form>
    </div>

</template>

<script>
import { postLogin } from '@/api'
export default {
  data () {
    return {
      loginForm: { username: 'admin', password: '123456' },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleLogin (formName) {
      this.$refs[formName].validate(isPass => {
        if (isPass) {
          postLogin(this.loginForm).then(res => {
            // console.log(res)
            if (res.meta.status === 200) {
              // 提示登录成功
              this.$message({
                message: '登录成功',
                type: 'success',
                duration: 1000
              })
              // 将token保存到本地
              localStorage.setItem('mytoken', res.data.token)
              // 跳转到主页
              setTimeout(() => {
                this.$router.push({ name: 'home' })
              }, 1000)
            }
          })
        } else {
          this.$message.error('请输入完整!')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  position: fixed;
  width: 100%;
  height: 100%;
  background-color: #2f4050;

  .container {
    position: absolute;
    left: 0;
    right: 0;
    width: 500px;
    padding: 0px 40px 15px 40px;
    margin: 200px auto;
    background: white;
    .u-face {
      position: relative;
      left: 50%;
      width: 140px;
      height: 140px;
      margin-left: -60px;
      margin-top: -60px;
      box-sizing: border-box;
      border-radius: 50%;
      border: 10px solid #fff;
      box-shadow: 0 1px 5px #ccc;
      overflow: hidden;
    }
    .login-btn {
      width: 100%;
      margin-bottom: 30px;
    }
  }
}

</style>
